import {ref, reactive} from 'vue'
import {defineStore} from 'pinia'
import {httpAppList} from '@/api/application.js'

const emptyApp = {
  avatar: "",
  character: "",
  demand: "",
  id: 0,
  introduction: "",
  knowledge_id: "",
  option_message: "",
  target: "",
  title: "",
}

const useAppStorage = defineStore('application', () => {
  const applications = ref([])
  const show = ref(false)
  const init = ref(false)
  const useApp = reactive({...emptyApp})

  const httpApplications = async () => {
    const response = await httpAppList({limit: 6, is_recommend: 1}).catch(() => null)
    if (!response) {
      return []
    }
    const {list} = response
    return list
  }

  const getApplications = async () => {
    if (!init.value) {
      applications.value = await httpApplications()
      init.value = true
    }
    return applications.value
  }

  const setShow = (value = true) => {
    show.value = value
  }

  const setUseApp = (appItem) => {
    Object.keys(emptyApp).forEach(key => {
      useApp[key] = appItem[key]
    })
  }

  const clearUseApp = () => {
    Object.keys(emptyApp).forEach(key => {
      useApp[key] = emptyApp[key]
    })
  }

  return {getApplications, show, setShow, useApp, setUseApp, clearUseApp}
})

export default useAppStorage